package services

import (
	wms "ez/apps/wms/document"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
)

func GetItemSkuAllForMonthSummary(year, month int) []*wms.ItemSku {
	skuCrud := wms.NewItemSkuCrud()
	list, err := skuCrud.FindBy(ss.M{}, []string{"text"}, 0, 0)
	ez.Try(err)
	return list
}

type MountSummaryRow struct {
	Item     *wms.ItemSku `json:"item"`
	In       float64      `json:"in"`
	Out      float64      `json:"out"`
	Left     float64      `json:"left"`
	DeptInW  []float64    `json:"deptIn"`
	DeptOut  []float64    `json:"deptOut"`
	InW      float64      `json:"inW"`
	OutW     float64      `json:"outW"`
	LeftW    float64      `json:"leftW"`
	DeptIn   []float64    `json:"deptInW"`
	DeptOutW []float64    `json:"deptOutW"`
}

func GetMonthSummaryForItem(year, month int, isWeight bool) []*MountSummaryRow {
	//items := GetItemSkuAllForMonthSummary(year, month)
	//limitChan := make(chan int, 10)
	//wg := sync.WaitGroup{}
	//wanted := make([]*MountSummaryRow, 0)
	//println("============")
	//
	////获取所有部门
	//crudDept := wms.NewDepartmentCrud()
	//depts, _ := crudDept.FindBy(ss.M{}, []string{"id"}, 0, 0)
	//idsInDept := make([]int, 0)
	//for _, dept := range depts {
	//	if !dept.IsShowIn {
	//		continue
	//	}
	//	idsInDept = append(idsInDept, dept.Id)
	//}
	//idsOutDept := make([]int, 0)
	//for _, dept := range depts {
	//	if !dept.IsShowOut {
	//		continue
	//	}
	//	idsOutDept = append(idsOutDept, dept.Id)
	//}
	//
	//for _, item := range items {
	//
	//	row := &MountSummaryRow{
	//		Item:     item,
	//		In:       0,
	//		Out:      0,
	//		Left:     0,
	//		DeptIn:   make([]float64, len(idsInDept)),
	//		DeptOut:  make([]float64, len(idsOutDept)),
	//		InW:      0,
	//		OutW:     0,
	//		LeftW:    0,
	//		DeptInW:  make([]float64, len(idsInDept)),
	//		DeptOutW: make([]float64, len(idsOutDept)),
	//	}
	//	wanted = append(wanted, row)
	//}
	//
	//crudIOType := wms.NewIOTypeCrud()
	//inTypes, _ := crudIOType.FindBy(ss.M{
	//	"parentId": 1,
	//}, nil, 0, 0)
	//outTypes, _ := crudIOType.FindBy(ss.M{
	//	"parentId": 2,
	//}, nil, 0, 0)
	//inIds := make([]int, 0)
	//for _, inType := range inTypes {
	//	inIds = append(inIds, inType.Id)
	//}
	//outIds := make([]int, 0)
	//for _, outType := range outTypes {
	//	outIds = append(outIds, outType.Id)
	//}
	//
	//for i, item := range items {
	//	wg.Add(1)
	//	limitChan <- 1
	//	//lk.Lock()
	//	go func(itemId, y, m int, r *MountSummaryRow, weight float64) {
	//		defer wg.Done()
	//		defer func() {
	//			<-limitChan
	//		}()
	//
	//		// 当月应该获取上个月的结余
	//		lastYear, lastMonth := GetLastMonth(year, month)
	//
	//		//数量数据
	//		r.In = GetItemMonthSummaryIn(itemId, y, m)
	//		r.Out = GetItemMonthSummaryOut(itemId, y, m)
	//		// 当月应该获取上个月的结余
	//		//lastYear, lastMonth := GetLastMonth(year, month)
	//		//ez.Debug(fmt.Sprintf("开始查询left内容year=%d,month=%d", lastYear, lastMonth))
	//		r.Left = GetItemMonthSummaryLeftLastMonth(itemId, lastYear, lastMonth, false)
	//		if r.Left != 0 {
	//			println(fmt.Sprintf("开始查询left内容itemId=%dyear=%d,month=%d,left=%f", itemId, lastYear, lastMonth, r.Left))
	//		}
	//		//r.Left = GetItemMonthSummaryLeftLastMonth(itemId, y, m)
	//		//println(itemId, y, m, r.In, r.Out)
	//
	//		// 获取入库各个部门的明细
	//		inDetail := GetItemMonthSummaryInForDept(itemId, year, month, inIds)
	//		for index, id := range idsInDept {
	//			r.DeptIn[index], _ = inDetail[id]
	//		}
	//		// 获取出库各个部门的明细
	//		outDetail := GetItemMonthSummaryOutForDept(itemId, year, month, outIds)
	//		for index, id := range idsOutDept {
	//			r.DeptOut[index], _ = outDetail[id]
	//		}
	//
	//		//重量数据
	//		r.InW = GetItemMonthSummaryInWeight(itemId, y, m)
	//		r.OutW = GetItemMonthSummaryOutWeight(itemId, y, m)
	//		// 当月应该获取上个月的结余
	//		//lastYear, lastMonth := GetLastMonth(year, month)
	//		//r.LeftW = GetItemMonthSummaryLeftWeightLastMonth(itemId, lastYear, lastMonth)
	//		r.LeftW = GetItemMonthSummaryLeftLastMonth(itemId, lastYear, lastMonth, true)
	//
	//		// 获取入库各个部门的明细
	//		inDetailW := GetItemMonthSummaryInWeightForDept(itemId, year, month, inIds)
	//		for index, id := range idsInDept {
	//			r.DeptInW[index], _ = inDetailW[id]
	//		}
	//		// 获取出库各个部门的明细
	//		outDetailW := GetItemMonthSummaryOutWeightForDept(itemId, year, month, outIds)
	//		for index, id := range idsOutDept {
	//			r.DeptOutW[index], _ = outDetailW[id]
	//		}
	//
	//		if isWeight {
	//
	//		} else {
	//
	//		}
	//
	//	}(item.Id, year, month, wanted[i], item.Weight)
	//}
	//wg.Wait()
	//return wanted
	return nil
}

// 获取ItemSku月份入库数据
func GetItemMonthSummaryIn(itemId, year, month int) (count float64) {
	//	wanted := make([]struct {
	//		Total float64 `json:"total"`
	//		Dept  int     `json:"dept"`
	//	}, 0)
	//	//start := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
	//	//end := time.Date(year, time.Month(month+1), 1, 0, 0, 0, 0, time.Local)
	//	tx := global.DB.Raw(`
	//SELECT sum(A.num) AS total
	//FROM wms_summary A
	//WHERE ( A.y = ? AND A.m = ? AND A.item_id = ? AND A.io_type = ? )
	//`, year, month, itemId, IoTypeIn).Find(&wanted)
	//	if tx.Error != nil {
	//		ez.Debug(tx.Error.Error())
	//	}
	//	if len(wanted) == 0 {
	//		return 0
	//	}
	//	return wanted[0].Total
	return 0
}
func GetItemMonthSummaryInWeight(itemId, year, month int) (count float64) {
	//	wanted := make([]struct {
	//		Total float64 `json:"total"`
	//		Dept  int     `json:"dept"`
	//	}, 0)
	//	//start := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
	//	//end := time.Date(year, time.Month(month+1), 1, 0, 0, 0, 0, time.Local)
	//	tx := global.DB.Raw(`
	//SELECT sum(A.weight) AS total
	//FROM wms_summary A
	//WHERE ( A.y = ? AND A.m = ? AND A.item_id = ? AND A.io_type = ? )
	//`, year, month, itemId, IoTypeIn).Find(&wanted)
	//	if tx.Error != nil {
	//		ez.Debug(tx.Error.Error())
	//	}
	//	if len(wanted) == 0 {
	//		return 0
	//	}
	//	return wanted[0].Total

	return 0
}
func GetItemMonthSummaryInForDept(itemId, year, month int, typeIds []int) map[int]float64 {
	//	start := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
	//	end := time.Date(year, time.Month(month+1), 1, 0, 0, 0, 0, time.Local)
	//	wanted := make([]struct {
	//		Total float64 `json:"total"`
	//		Dept  int     `json:"dept"`
	//	}, 0)
	//
	//	tx := global.DB.Raw(`
	//SELECT sum(A.num_in) AS total,A.department_id as dept
	//FROM wms_in_log A
	//Left Join wms_department B ON A.department_id = B.id
	//WHERE ( A.create_at >= ? AND A.create_at <= ? AND A.item_id = ? AND A.type_id In ? AND B.is_show_in = 1)
	//GROUP BY A.department_id
	//`, start, end, itemId, typeIds).Find(&wanted)
	//	re := make(map[int]float64)
	//	for _, s := range wanted {
	//		re[s.Dept] = s.Total
	//	}
	//	if tx.Error != nil {
	//		ez.Debug(tx.Error.Error())
	//	}
	//	return re

	return nil
}
func GetItemMonthSummaryInWeightForDept(itemId, year, month int, typeIds []int) map[int]float64 {
	//	start := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
	//	end := time.Date(year, time.Month(month+1), 1, 0, 0, 0, 0, time.Local)
	//	wanted := make([]struct {
	//		Total float64 `json:"total"`
	//		Dept  int     `json:"dept"`
	//	}, 0)
	//
	//	tx := global.DB.Raw(`
	//SELECT sum(A.cost) AS total,A.department_id as dept
	//FROM wms_in_log A
	//Left Join wms_department B ON A.department_id = B.id
	//WHERE ( A.create_at >= ? AND A.create_at <= ? AND A.item_id = ? AND A.type_id In ? AND B.is_show_in = 1)
	//GROUP BY A.department_id
	//`, start, end, itemId, typeIds).Find(&wanted)
	//	re := make(map[int]float64)
	//	for _, s := range wanted {
	//		re[s.Dept] = s.Total
	//	}
	//	if tx.Error != nil {
	//		ez.Debug(tx.Error.Error())
	//	}
	//	return re
	return nil
}

func GetItemMonthSummaryOutForDept(itemId, year, month int, typeIds []int) map[int]float64 {
	//	start := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
	//	end := time.Date(year, time.Month(month+1), 1, 0, 0, 0, 0, time.Local)
	//	wanted := make([]struct {
	//		Total float64 `json:"total"`
	//		Dept  int     `json:"dept"`
	//	}, 0)
	//
	//	tx := global.DB.Raw(`
	//SELECT sum(A.num) AS total,A.department_id as dept
	//FROM wms_out_log A
	//Left Join wms_department B  ON A.department_id = B.id
	//WHERE ( A.create_at >= ? AND A.create_at <= ? AND A.item_id = ? AND A.type_id In ? AND B.is_show_out = 1)
	//GROUP BY A.department_id
	//`, start, end, itemId, typeIds).Find(&wanted)
	//	re := make(map[int]float64)
	//	for _, s := range wanted {
	//		re[s.Dept] = s.Total
	//	}
	//	if tx.Error != nil {
	//		ez.Debug(tx.Error.Error())
	//	}
	//	return re
	return nil
}

func GetItemMonthSummaryOutWeightForDept(itemId, year, month int, typeIds []int) map[int]float64 {
	//	start := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
	//	end := time.Date(year, time.Month(month+1), 1, 0, 0, 0, 0, time.Local)
	//	wanted := make([]struct {
	//		Total float64 `json:"total"`
	//		Dept  int     `json:"dept"`
	//	}, 0)
	//
	//	tx := global.DB.Raw(`
	//SELECT sum(A.cost) AS total,A.department_id as dept
	//FROM wms_out_log A
	//Left Join wms_department B  ON A.department_id = B.id
	//WHERE ( A.create_at >= ? AND A.create_at <= ? AND A.item_id = ? AND A.type_id In ? AND B.is_show_out = 1)
	//GROUP BY A.department_id
	//`, start, end, itemId, typeIds).Find(&wanted)
	//	re := make(map[int]float64)
	//	for _, s := range wanted {
	//		re[s.Dept] = s.Total
	//	}
	//	if tx.Error != nil {
	//		ez.Debug(tx.Error.Error())
	//	}
	//	return re
	return nil
}

func GetItemMonthSummaryOut(itemId, year, month int) (count float64) {
	//	wanted := make([]struct {
	//		Total float64 `json:"total"`
	//		Dept  int     `json:"dept"`
	//	}, 0)
	//	//start := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
	//	//end := time.Date(year, time.Month(month+1), 1, 0, 0, 0, 0, time.Local)
	//	tx := global.DB.Raw(`
	//SELECT sum(A.num) AS total
	//FROM wms_summary A
	//WHERE ( A.y = ? AND A.m = ? AND A.item_id = ? AND A.io_type = ? )
	//`, year, month, itemId, IoTypeOut).Find(&wanted)
	//	if tx.Error != nil {
	//		ez.Debug(tx.Error.Error())
	//	}
	//	if len(wanted) == 0 {
	//		return 0
	//	}
	//	return wanted[0].Total
	return 0
}

func GetItemMonthSummaryOutWeight(itemId, year, month int) (count float64) {
	//	wanted := make([]struct {
	//		Total float64 `json:"total"`
	//		Dept  int     `json:"dept"`
	//	}, 0)
	//	//start := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local)
	//	//end := time.Date(year, time.Month(month+1), 1, 0, 0, 0, 0, time.Local)
	//	tx := global.DB.Raw(`
	//SELECT sum(A.weight) AS total
	//FROM wms_summary A
	//WHERE ( A.y = ? AND A.m = ? AND A.item_id = ? AND A.io_type = ? )
	//`, year, month, itemId, IoTypeOut).Find(&wanted)
	//	if tx.Error != nil {
	//		ez.Debug(tx.Error.Error())
	//	}
	//	if len(wanted) == 0 {
	//		return 0
	//	}
	//	return wanted[0].Total
	return 0
}

func GetItemMonthSummaryLeftLastMonth(itemId, year, month int, isWeight bool) (count float64) {
	////这里的年和月是已经计算好的
	//crud := wms.NewSummaryCrud()
	//wanted, e := crud.FindOneBy(ss.M{
	//	"itemId": itemId,
	//	"ioType": IoTypeLeft,
	//	"y":      year,
	//	"m":      month}, []string{"id"})
	//
	//if e != nil {
	//	// 这里如果获取不到当月的结存记录有几种情况：1.当月没有入库记录，2.当月没有出库记录，3.当月没有入库出库记录
	//	//计算该项目每个月的结存数据
	//	println(fmt.Sprintf("NF%d-%d-%d", itemId, year, month))
	//	return CalcItemMonthSummaryAndCreateLog(itemId, year, month, isWeight)
	//} else {
	//	curYear := time.Now().Year()
	//	curMonth := int(time.Now().Month())
	//
	//	if year*100+month >= curYear*100+curMonth {
	//		//更新当月数据
	//		//获取当前项目最早的汇总记录
	//		list, _ := crud.FindBy(ss.M{
	//			"itemId":     itemId,
	//			"ioType__in": []int{IoTypeIn, IoTypeOut},
	//			"y":          year,
	//			"m":          month}, []string{"id"}, 0, 0)
	//		//获取当前项目最早的汇总记录
	//		total := 0.0
	//		for _, item := range list {
	//			switch item.IoType {
	//			case IoTypeIn:
	//				total += item.Num
	//			case IoTypeOut:
	//				total -= item.Num
	//			}
	//		}
	//		totalWeight := 0.0
	//		for _, item := range list {
	//			switch item.IoType {
	//			case IoTypeIn:
	//				totalWeight += item.Weight
	//			case IoTypeOut:
	//				totalWeight -= item.Weight
	//			}
	//		}
	//		wanted.Weight = totalWeight
	//		wanted.Num = total
	//		wanted.Save()
	//		if isWeight {
	//			return totalWeight
	//		}
	//		return total
	//	}
	//}
	//if isWeight {
	//	return wanted.Weight
	//}
	//return wanted.Num
	return 0
}

func CalcItemMonthSummaryAndCreateLog(itemId int, wantedYear int, wantedMonth int, isWeight bool) (count float64) {
	////获取当前项目最早的汇总记录
	//crud := wms.NewSummaryCrud()
	//find, _ := crud.FindOneBy(ss.M{
	//	"itemId": itemId,
	//}, []string{"ymd"})
	//
	//itemSku := wms.ItemSku{
	//	Id: itemId,
	//}
	//itemSku.Read()
	//if find.Id == 0 {
	//	// 如果这个产品一个记录都没有
	//	//find = &wms.Summary{
	//	//	ItemId:   itemId,
	//	//	Item:     &itemSku,
	//	//	ItemName: fmt.Sprintf("%s_%s", itemSku.Text, itemSku.Code),
	//	//	Ymd:      wantedYear*10000 + wantedMonth*100,
	//	//	Y:        wantedYear,
	//	//	M:        wantedMonth,
	//	//	IoType:   IoTypeLeft,
	//	//}
	//	//find.Save(false)
	//	return 0
	//}
	//if find.Y*100+find.M > wantedYear*100+wantedMonth {
	//	//如果当月的汇总记录已经大于想要的月份，说明没有更早的数据了，则直接返回
	//
	//	//find = &wms.Summary{
	//	//	ItemId:   itemId,
	//	//	Item:     &itemSku,
	//	//	ItemName: fmt.Sprintf("%s_%s", itemSku.Text, itemSku.Code),
	//	//	Ymd:      wantedYear*10000 + wantedMonth*100,
	//	//	Y:        wantedYear,
	//	//	M:        wantedMonth,
	//	//	IoType:   IoTypeLeft,
	//	//}
	//	//find.Save(false)
	//	return 0
	//}
	////获取当月份的年和月，如果下一个月份的数字与当前月份的数字相等，则停止
	//curYear := time.Now().Year()
	//curMonth := int(time.Now().Month())
	//year := find.Y
	//month := find.M
	//
	//lastCount := 0.0
	//lastWeight := 0.0
	//wantedCount := 0.0
	//for {
	//	if year*100+month > curYear*100+curMonth {
	//		break
	//	} else {
	//		//创建汇总记录
	//		//1.先检查是否存在该记录
	//		find, _ = crud.FindOneBy(ss.M{
	//			"itemId": itemId,
	//			"ioType": IoTypeLeft,
	//			"y":      year,
	//			"m":      month}, []string{"id"})
	//		if find.Id == 0 {
	//			//不存在，则创建
	//			find = &wms.Summary{
	//				ItemId:   itemId,
	//				Item:     &itemSku,
	//				ItemName: fmt.Sprintf("%s_%s", itemSku.Text, itemSku.Code),
	//				Ymd:      year*10000 + month*100,
	//				Y:        year,
	//				M:        month,
	//				IoType:   IoTypeLeft,
	//			}
	//			find.Save(false)
	//		} else {
	//			//存在，则更新
	//		}
	//		//获取当前项目最早的汇总记录
	//		list, _ := crud.FindBy(ss.M{
	//			"itemId":     itemId,
	//			"ioType__in": []int{IoTypeIn, IoTypeOut},
	//			"y":          year,
	//			"m":          month}, []string{"id"}, 0, 0)
	//		//获取当前项目最早的汇总记录
	//		total := lastCount
	//		for _, item := range list {
	//			switch item.IoType {
	//			case IoTypeIn:
	//				total += item.Num
	//			case IoTypeOut:
	//				total -= item.Num
	//			}
	//		}
	//		totalWeight := lastWeight
	//		for _, item := range list {
	//			switch item.IoType {
	//			case IoTypeIn:
	//				totalWeight += item.Weight
	//			case IoTypeOut:
	//				totalWeight -= item.Weight
	//			}
	//		}
	//		find.Num = total
	//		find.Weight = totalWeight
	//
	//		lastCount = total
	//		lastWeight = totalWeight
	//		find.Save(true)
	//		if year == wantedYear && month == wantedMonth {
	//			if isWeight {
	//				wantedCount = totalWeight
	//			} else {
	//				wantedCount = total
	//			}
	//		}
	//
	//		year, month = GetNextMonth(year, month)
	//	}
	//}
	//if wantedCount == 0 {
	//	wantedCount = lastCount
	//	if isWeight {
	//		wantedCount = lastWeight
	//	} else {
	//		wantedCount = lastCount
	//	}
	//}
	//return wantedCount
	return 0
}

// 根据年和月的数字计算下一个月份的年和月
func GetNextMonth(year, month int) (int, int) {
	if month == 12 {
		return year + 1, 1
	} else {
		return year, month + 1
	}
}

func GetLastMonth(year, month int) (int, int) {
	if month == 1 {
		return year - 1, 12
	} else {
		return year, month - 1
	}
}
